package com.diamond.webservice.util;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.MessageFormat;

/**
 * json使用alibaba.fastjson
 * @author 王丹梦
 * Jaxb2.0 处理Xml与Object转换
 */
public class JaxbObjectAndXmlUtil {
    /**
     * 此处使用了Stringreader，其实Unmarshaller接口还支持
     * File，InputStream，URL，StringBuffer，org.w3c.dom.Node等反序列化
     * API连接
     * http://tool.oschina.net/uploads/apidocs/jdk-zh/javax/xml/bind/Unmarshaller.html
     * @param xmlStr 字符串
     * @param c 对象Class类型
     * @return 对象实例
     */
    @SuppressWarnings({ "unchecked", "finally" })
    public static <T> T xml2Object(String xmlStr,Class<T> c){
        try{
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            T t = (T) unmarshaller.unmarshal(new StringReader(xmlStr));
            return t;
        } catch (JAXBException e) {
            e.printStackTrace();  return null;
        }
    }

    /**
     * 可变参数
     * config里使用占位符 {0}  {1}  {2}，单引号要使用两个
     * MessageFormat使用链接
     * @param config
     * @param c
     * @param arguments
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T xml2Object(String config,Class<T> c,Object... arguments){
        try{
            if (arguments.length > 0) {
                config = MessageFormat.format(config, arguments);
            }
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            T t = (T) unmarshaller.unmarshal(new StringReader(config));
            return t;
        } catch (JAXBException e) {
            e.printStackTrace();  return null;
        }
    }

    /**
     * @param object 对象
     * @return 返回xmlStr
     */
    public static String object2Xml(Object object){
        try{
            StringWriter writer = new StringWriter();
            JAXBContext context = JAXBContext.newInstance(object.getClass());
            Marshaller marshal = context.createMarshaller();
            marshal.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 格式化输出
            marshal.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);    // 是否省略xml头信息 是
            marshal.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// 编码格式,默认为utf-8
            writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
            marshal.marshal(object,writer);
            return new String(writer.getBuffer());
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
